﻿using Newtonsoft.Json;
using System.Security.Cryptography;
using System.Text;

namespace HLStock.Common
{
    public static class Utils
    {
        public static string Serialize(object data)
        {
            return JsonConvert.SerializeObject(data);
        }
        public static T? Deserialize<T>(string str)
        {
            return JsonConvert.DeserializeObject<T>(str);
        }

        public static T Clone<T>(T data)
        {
            return Deserialize<T>(Serialize(data));
        }
        public static void Restore<T>(T data, T backup)
        {
            foreach (var p in typeof(T).GetProperties())
            {
                p.SetValue(data, p.GetValue(backup));
            }
        }
        public static string MakePassword()
        {
            const string seed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.!@#$%^&*()_+=";
            return RandomNumberGenerator.GetString(seed, 8);
        }
        public static string Md5(string str)
        {
            if (String.IsNullOrWhiteSpace(str)) return "";
            string pwd = "";
            MD5 md5 = MD5.Create();
            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
            for (int i = 0; i < s.Length; i++)
            {
                pwd = pwd + s[i].ToString("X2");
            }
            return pwd.ToUpper();
        }
        static int counter = 10000;
        static Random random = new Random();
        static object locker = new object();
        public static string CreatePk()
        {
            lock (locker)
            {
                if (counter >= 100000) counter = 10000;
                else counter++;
            }
            int r = random.Next(0, 9);
            string dt = DateTime.Now.ToString("yyMMddHHmmssfff");
            return dt + counter.ToString().Substring(1, 4) + r;
        }
    }
}
